<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :before-open="beforeOpen"
      :search.sync="search"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <!-- <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-el-icon-bottom" plain v-if="permission.workshop_delete" @click="handleDelete">数据导出</el-button>
      </template> -->
      <template slot-scope="{ row }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.testDataCollection_view" @click="viewDetail(row)">详情</el-button>
      </template>
      <template slot-scope="" slot="operatorNameSearch">
        <el-input placeholder="请选择 操作人" readonly="true" v-model="search.operatorName">
          <el-button slot="append" icon="el-icon-search" @click="openUserCommonModal"></el-button>
        </el-input>
      </template>
      <template slot-scope="" slot="workOrderNoSearch">
        <el-input placeholder="请选择 工单号" readonly="true" v-model="search.workOrderNo">
          <el-button slot="append" icon="el-icon-search" @click="openWorkOrderNoCommonModal"></el-button>
        </el-input>
      </template>
      <template slot-scope="" slot="productPartNoSearch">
        <el-input placeholder="请选择 产品编码" readonly="true" v-model="search.productPartNo">
          <el-button slot="append" icon="el-icon-search" @click="openPartNoCommonModal"></el-button>
        </el-input>
      </template>
    </avue-crud>
    <el-dialog v-dragDirectives ref="dialog" title="详情" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" top="5vh" @close="closeDialog">
      <avue-crud
        :option="productDataDetailListOption"
        :table-loading="detailLoading"
        :data="productDataDetail"
        :page.sync="detailPage"
        @search-change="detailSearchChange"
        @search-reset="detailSearchReset"
        @current-change="detailCurrentChange"
        @size-change="detailSizeChange"
      >
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <export-comp ref="exportComp" page-api-url="mes-abacus/statoperator/page-query" :option="option" :page="page" :query="query" file-name="人员产出"> </export-comp>
  </basic-container>
</template>

<script>
import { getList, getDetail } from '@/api/report/personnel-qutput-query';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList as getProductionlineList } from '@/api/product/productionline';
import { getList as getStationList } from '@/api/product/station';
import exportComp from '@/components/export-comp';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'ReportPersonnelQutputQuery',
  components: {
    CommonModalTemplate,
    userTableConfig,
    exportComp
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'PERSONNEL_QUTPUT_QUERY',
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      form: {},
      exprotVisible: false,
      exportData: [],
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      search: {},
      selectionList: [],
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 4,
        labelWidth: 100,
        searchLabelWidth: 90,
        border: true,
        index: true,
        editBtn: false,
        viewBtn: false,
        selection: true,
        delBtn: false,
        addBtn: false,
        dialogClickModal: false,
        indexLabel: '序号',
        searchMenuPosition: 'right',
        columnBtn: false,
        menuWidth: 100,
        column: [
          {
            label: '窗口统计时间',
            width: 130,
            prop: 'windowTime',
            searchType: 'datetime',
            format: 'yyyy-MM-dd HH',
            valueFormat: 'yyyy-MM-dd HH'
          },
          {
            label: '操作人',
            prop: 'operatorAccount'
          },
          {
            label: '操作人姓名',
            prop: 'operatorName',
            search: true,
            searchOrder: 4
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true,
            searchOrder: 5
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true,
            searchOrder: 6
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: '车间名称',
            prop: 'workshopId',
            type: 'select',
            search: true,
            searchOrder: 1,
            dicUrl: '/api/mes-admin/workshop/key-value',
            props: {
              label: 'workshopName',
              value: 'workshopId'
            }
          },
          {
            label: '产线',
            prop: 'lineId',
            search: true,
            searchOrder: 2,
            type: 'select',
            dicData: [],
            hide: true
          },
          {
            label: '产线',
            prop: 'lineName'
          },
          {
            label: '工位名称',
            prop: 'stationId',
            search: true,
            searchOrder: 3,
            type: 'select',
            dicData: [],
            hide: true
          },
          {
            label: '工位',
            prop: 'stationName'
          },
          {
            label: '过站工序',
            prop: 'routeName'
          },
          {
            label: 'Fail次数',
            prop: 'ngCount'
          },
          {
            label: '合格数',
            prop: 'actualPassQuantity'
          },
          {
            label: '不良数',
            prop: 'actualNgQuantity'
          },
          {
            label: '选择时间',
            prop: 'createTime',
            popperClass: 'personnelQutputQueryClass',
            search: true,
            searchSpan: 6,
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH',
            valueFormat: 'yyyy-MM-dd HH',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            hide: true,
            searchRules: [
              {
                required: true,
                message: '请选择时间',
                trigger: 'blur'
              }
            ]
          }
          // {
          //   label: '窗口时间',
          //   prop: 'windowTime',
          //   search: true,
          //   searchSpan: 6,
          //   searchType: 'timerange',
          //   format: 'HH',
          //   valueFormat: 'HH:mm:ss',
          //   startPlaceholder: '窗口开始时间',
          //   endPlaceholder: '窗口结束时间',
          //   hide: true,
          //   popperClass: 'window-time'
          // }
        ]
      },
      data: [],
      detailLoading: true,
      showDialog: false,
      productDataDetailListOption: {
        height: '500',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        labelWidth: 100,
        border: true,
        index: true,
        viewBtn: false,
        selection: false,
        dialogClickModal: false,
        indexLabel: '序号',
        menu: false,
        refreshBtn: false,
        columnBtn: false,
        addBtn: false,
        column: [
          {
            label: '条码类型',
            prop: 'type',
            type: 'select',
            dicData: [
              {
                label: '产品序列号',
                value: 'PRODUCT'
              },
              {
                label: '包装条码',
                value: 'PACKING'
              },
              {
                label: '载具',
                value: 'CARRIER'
              }
            ]
          },
          {
            label: '序列号',
            prop: 'sequenceNumber',
            search: true
          },
          {
            label: '产品数量',
            prop: 'quantity'
          },
          {
            label: '是否合格',
            prop: 'result',
            type: 'select',
            dicData: [
              {
                label: '合格',
                value: 'PASS'
              },
              {
                label: '不合格',
                value: 'FAIL'
              }
            ]
          },
          {
            label: '过站时间',
            prop: 'transactionTime'
          }
        ]
      },
      productDataDetail: [],
      currentRow: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  watch: {
    'search.workshopId'(val) {
      this.search.lineId = '';
      const column = this.findObject(this.option.column, 'lineId');
      column.dicData = [];
      if (val) {
        getProductionlineList(1, 10000, { workshopId: val })
          .then((res) => {
            column.dicData = this._get(res, 'data.data.records', []);
            column.dicData = this._map(column.dicData, (item) => {
              return {
                label: item.name,
                value: item.id
              };
            });
          })
          .catch((err) => {
            column.dicData = [];
          });
      }
    },
    'search.lineId'(val) {
      this.search.stationId = '';
      const column = this.findObject(this.option.column, 'stationId');
      column.dicData = [];
      if (val) {
        getStationList(1, 10000, { lineId: val })
          .then((res) => {
            column.dicData = this._get(res, 'data.data.records', []);
            column.dicData = this._map(column.dicData, (item) => {
              return {
                label: item.name,
                value: item.id
              };
            });
          })
          .catch((err) => {
            column.dicData = [];
          });
      }
    }
  },
  created() {
    let startDate = this.$moment(new Date()).format('YYYY-MM-DD');
    let endDate = this.$moment(new Date()).format('YYYY-MM-DD');
    startDate = startDate + ' ' + '00:00:00';
    endDate = endDate + ' ' + '23:00:00';
    this.$set(this.search, 'createTime', [startDate, endDate]);
    this.query.createTime = this.search.createTime;
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail({ id: this.form.id, ...this.query }).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
    },
    searchChange(params, done) {
      if (params.routeName) {
        params.routeCode = params.routeName;
        delete params.routeName;
      }
      if (params.deptId) {
        params.deptName = params.deptId;
        delete params.deptId;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    handleSelectData(val) {
      let current = 1;
      let pageSize = this.page.pageSize;
      if (val === 'all') {
        // 接口返回上限500条数据
        pageSize = 500;
      } else {
        current = this.page.currentPage;
      }
      const page = {
        current,
        pageSize
      };
      this.onLoad(page);
    },
    handleExport() {
      this.exportData = this.data;
      this.exprotVisible = true;
    },
    handleClose(val) {
      this.exprotVisible = false;
      this.data = this.exportData.splice(0, this.page.pageSize);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (this.query.createTime) {
        this.query.startTime = this.$moment(this.query.createTime[0]).format('YYYY-MM-DD HH:00:00');
        this.query.endTime = this.$moment(this.query.createTime[1]).format('YYYY-MM-DD HH:00:00');
        // if (this.query.windowTime) {
        //   const windowTime = this.query.windowTime.split(',');
        //   this.query.startWindowHour = windowTime ? this.$moment(windowTime[0], 'HH').startOf('hour').format('HH:00:00') : '';
        //   this.query.endWindowHour = windowTime ? this.$moment(windowTime[1], 'HH').startOf('hour').format('HH:00:00') : '';
        // }
        delete this.query.createTime;
        delete this.query.windowTime;
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.exportData = this.data;
        this.loading = false;
        this.selectionClear();
      });
    },
    // 下载
    openDownload(row) {
      if (row.fileUrl) {
        this.globalStartLoad('文件下载中，请稍后...');
        downloadFileByUrl(row.fileUrl, row.fileName);
        this.globalEndLoad();
      }
    },

    viewDetail(row) {
      this.showDialog = true;
      this.testDataDetail = row;
      this.testDataDetailResult = [];
      this.detailPage.currentPage = 1;
      this.detailOnLoad(row);
    },
    /**
     * 打开操作人员列表模态框
     */
    openUserCommonModal() {
      this.modalName = 'userModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择操作人（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '登录账号',
            prop: 'account',
            search: true,
            display: false
          },
          {
            label: '所属租户',
            prop: 'tenantName',
            slot: true,
            display: false
          },
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            display: false
          },
          {
            label: '所属角色',
            prop: 'roleName',
            slot: true,
            display: false
          },
          {
            label: '所属部门',
            prop: 'deptName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            prop: 'userTypeName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=user_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dataType: 'number',
            search: true,
            hide: true,
            display: false,
            prop: 'userType',
            rules: [
              {
                required: true,
                message: '请选择用户平台',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    openWorkOrderNoCommonModal() {
      this.modalName = 'workOrderNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select'
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    openPartNoCommonModal() {
      this.modalName = 'partNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品信息（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=true',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '类型',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          }
        ]
      };
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'userModal':
          this.search.operatorName = this._get(rowData, 'realName', '');
          break;
        case 'workOrderNoModal':
          this.search.workOrderNo = this._get(rowData, 'orderNo', '');
          this.search.productPartNo = this._get(rowData, 'partNo', '');
          break;
        case 'partNoModal':
          this.search.productPartNo = this._get(rowData, 'partNo', '');
          break;
      }
    },
    detailCurrentChange(currentPage) {
      this.detailPage.currentPage = currentPage;
      this.detailOnLoad(this.currentRow);
    },
    detailSizeChange(pageSize) {
      this.detailPage.pageSize = pageSize;
      this.detailOnLoad(this.currentRow);
    },
    detailSearchChange(params, done) {
      this.detailQuery = params;
      this.detailPage.currentPage = 1;
      this.queryDetail();
      done();
    },
    detailSearchReset() {
      this.detailQuery = {};
      this.queryDetail(this.detailPage);
    },
    detailOnLoad(row) {
      this.currentRow = row;
      this.queryDetail();
    },
    queryDetail(params = {}) {
      this.detailLoading = true;
      getDetail(
        {
          workshopId: this.currentRow.workshopId,
          stationId: this.currentRow.stationId,
          operatorId: this.currentRow.operatorId,
          routeId: this.currentRow.routeId,
          productPartMasterId: this.currentRow.productPartMasterId,
          lineId: this.currentRow.lineId,
          windowTime: this.currentRow.windowTime,
          workOrderId: this.currentRow.workOrderId
          // startDate: this.query.startDate.replace('00:00:00', this.query.startWindowHour || '00:00:00'),
          // endDate: this.query.endDate.replace('00:00:00', this.query.endWindowHour || '00:00:00')
        },
        this.detailPage.currentPage,
        this.detailPage.pageSize,
        Object.assign(params, this.detailQuery)
      ).then((res) => {
        const data = res.data.data;
        this.detailPage.total = data.total;
        this.productDataDetail = data.records;
        this.detailLoading = false;
      });
    }
  }
};
</script>

<style lang="scss">
.window-time {
  .el-scrollbar:nth-of-type(2) {
    display: none !important;
  }
}

.personnelQutputQueryClass .el-time-spinner__wrapper {
  width: 100% !important;
}
</style>
